using System;

namespace hemsidan.Entities
{
	/// <summary>
	/// Summary description for Blog.
	/// </summary>
	public class Blog
	{
		public Blog()
		{
		}


		public static System.Data.DataTable GetRecent(int count)
		{
			string sql = "select * from BlogItem order by Created desc LIMIT 0," + count.ToString();
			System.Data.DataTable table = DataAccess.DB.getInstance().ExecuteDataSet(sql).Tables[0];

			for(int i=count; table.Rows.Count > i; i++)
			{
				table.Rows.RemoveAt(i);
			}
			return table;
		}
		public static System.Data.DataTable GetBlog(int BlogId)
		{
			string sql = "select * from BlogItem where Id=" + BlogId.ToString();
			return DataAccess.DB.getInstance().ExecuteDataSet(sql).Tables[0];
		}
        public static System.Data.DataTable GetMonths(int year, int monthNo)
        {
            DateTime startDate = new DateTime(year,monthNo,1);
            DateTime endDate = startDate.AddMonths(1).AddDays(-1);
            return GetPeriod(startDate, endDate);
        }

        public static System.Data.DataTable GetYears(int year)
        {
            DateTime startDate = new DateTime(year,1,1);
            DateTime endDate = new DateTime(year,12,31);
            return GetPeriod(startDate, endDate);
        }

        private static System.Data.DataTable GetPeriod(DateTime startDate, DateTime endDate)
        {
            string sql = "select * from BlogItem where Created >= '" + startDate.ToString("yyyy-MM-dd") + "' and Created <='" + endDate.ToString("yyyy-MM-dd") + "' order by Created desc";
            System.Data.DataTable table = DataAccess.DB.getInstance().ExecuteDataSet(sql).Tables[0];
            return table;
        }



		public static void CreateBlog(string Header, string TextField)
		{
			TextField = PrepText(TextField);
			string sql = "insert into BlogItem (Header, TextField) values ('" + Header + "', '" + TextField + "')";
			DataAccess.DB.getInstance().ExecuteNonQuery(sql);
		}

		public static void UpdateBlog(int BlogId, string Header, string TextField)
		{
			TextField = PrepText(TextField);
			string sql = "update BlogItem set Header='" + Header + "', TextField='" + TextField + "' where Id=" + BlogId;
			DataAccess.DB.getInstance().ExecuteNonQuery(sql);
		}

		public static void DeleteBlog(int BlogId)
		{
			string sql = "delete from BlogItem where Id=" + BlogId.ToString();
			DataAccess.DB.getInstance().ExecuteNonQuery(sql);
		}

		private static string PrepText(string TextField)
		{
			TextField = TextField.Replace("\n","<br>");
			return TextField;
		}

		
	}
}
